// The Nature of Code
// <http://www.shiffman.net/teaching/nature>
// Spring 2010
// PBox2D example

// An uneven surface boundary

class Surface implements ISurface {
  // We'll keep track of all of the surface points
  ArrayList<Vec2> surface;
  Body body;


  Surface(PVector []  pointlist) {
    surface = new ArrayList<Vec2>();

    // This is what box2d uses to put the surface in its world
    EdgeChainDef edges = new EdgeChainDef();
   
    float minX =0;
    float minY = 0;
    float maxY = 0;
    float maxX = 0;
    
    
    for(int i = 0; i < pointlist.length; i++)
    {
      PVector temp = (PVector)pointlist[i];
      println("Surface points: ("+ temp.x + "/"+ temp.y +")");
      
      if(i == 0) {
        minX = temp.x;
        maxX = temp.x;
        minY = temp.y;
        maxY = temp.y;
      }
      
      if(temp.x < minX) 
        minX = temp.x;
      
      if(temp.x > maxX)
        maxX = temp.x;
      if(temp.y < minY)
        minY = temp.y;
      if(temp.y > maxY)
        maxY = temp.y;
    }
    println("Surface End \n");
    
    Vec2 screenEdge;
    Vec2 edge;
    
    
    screenEdge = new Vec2(minX,maxY);
      // We store it for rendering
    surface.add(screenEdge);

      // Convert it to the box2d world and add it to our EdgeChainDef
    edge = box2d.coordPixelsToWorld(screenEdge);
    edges.addVertex(edge);
    
    screenEdge = new Vec2(maxX,maxY);
      // We store it for rendering
    surface.add(screenEdge);

      // Convert it to the box2d world and add it to our EdgeChainDef
    edge = box2d.coordPixelsToWorld(screenEdge);
    edges.addVertex(edge);    
    
    
    screenEdge = new Vec2(maxX,minY);
      // We store it for rendering
    surface.add(screenEdge);

      // Convert it to the box2d world and add it to our EdgeChainDef
    edge = box2d.coordPixelsToWorld(screenEdge);
    edges.addVertex(edge);
    
    screenEdge = new Vec2(minX,minY);
      // We store it for rendering
    surface.add(screenEdge);

      // Convert it to the box2d world and add it to our EdgeChainDef
    edge = box2d.coordPixelsToWorld(screenEdge);
    edges.addVertex(edge);    
    
 
    
    
    edges.setIsLoop(true);   // We could make the edge a full loop
    edges.friction = 2.0;    // How much friction
    edges.restitution = 0.3; // How bouncy

    // The edge chain is now a body!
    BodyDef bd = new BodyDef();
    bd.position.set(0.0f,0.0f);
    body = box2d.world.createBody(bd);
    body.createShape(edges);

  }

  // A simple function to just draw the edge chain as a series of vertex points
  void display() {
    strokeWeight(2);
    stroke(0);
    noFill();
    beginShape();
    for (Vec2 v: surface) {
      vertex(v.x,v.y);
    }
    Vec2 tmp = (Vec2)surface.get(0);
    vertex(tmp.x,tmp.y);
    endShape();
  }
  
  void killBody() {
    box2d.destroyBody(body);
  }

}


